package com.hnnu.shoppingtoghter.demo.controller;

import com.hnnu.shoppingtoghter.demo.entity.SysUser;
import com.hnnu.shoppingtoghter.demo.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: Liu aihuan
 * @CreateTime： 2022/7/8 2:18
 */
@Slf4j
@Controller
public class ImageController {

    @Autowired
    private SysUserService userService;

    @GetMapping("/my_head")
    public String getUploadPathImage() {

        return "my_head";
    }

    /** 上传图片的保存目录 */
    private static final String UPLOAD_PATH_IMAGE = "D:\\upload\\images\\";
    /** 允许上传的图片类型 */
    private static final String[] ALLOWED_EXTENSIONS_IMAGE = {"jpg", "png", "bmp"};
    private static final String DOWNLOAD_IMAGE_PATH = "/download/image/";

    /**
     * @Description: 图片上传
     * @Author: Liu aihuan
     * @CreateTime: 2022/7/2 18:22
     * @param: file 上传的图片
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     **/
    @PostMapping("/upload/image")
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        /** 封装响应结果信息 */
        Map<String, Object> result = new HashMap<>();
        /** 1、判断文件是否为空 */
        if(file.isEmpty()){
            log.error("uploadFile == 上传的文件为空！");
            result.put("code", "10001");
            result.put("msg", "请求失败， 上传的文件为空");
            return result;
        }
        /** 2、获取文件名 */
        String fileName = file.getOriginalFilename();
        /** 3、获取文件类型（扩展名），并进行校验 */
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!isValidExtension(suffixName, ALLOWED_EXTENSIONS_IMAGE)){
            log.error("文件类{}不符合要求，请重新上传！", suffixName);
            result.put("code", "10001");
            result.put("msg", "请求失败， 文件类不符合要求");
            return result;
        }
        /** 4、上传图片，并写入指定位置 */
        File desc = new File(UPLOAD_PATH_IMAGE + fileName);
        file.transferTo(desc);
        /** 5、封装成功上传的结果信息，并将图片地址返回给用户 */
        result.put("code", "200");
        result.put("url", DOWNLOAD_IMAGE_PATH + fileName);
        result.put("msg", "上传成功");
        return result;
    }

    /**
     * 验证上传的文件扩展名是否在允许范围内
     * @param extension 要上传的文件扩展名
     * @param extensions    允许上传的文件扩展名数组
     * @return
     */
    private boolean isValidExtension(String extension, String[] extensions){
        for(String allowedExtension : extensions){
            if(extension.equalsIgnoreCase(allowedExtension)){
                return true;
            }
        }
        return false;
    }


    /** 下载图片方式二 ：通过 FileCopyUtils  */
    @GetMapping("/download/image/{filename}")
    public void downloadImage1(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable("filename") String fileName) throws Exception {
        String filePath = UPLOAD_PATH_IMAGE + fileName;
        File file = new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在！");
        }

        ServletContext servletContext = request.getServletContext();
        String mimeType = servletContext.getMimeType(filePath);
        log.info("文件{}的MIME类型是：{}",fileName,mimeType);
        response.reset();
        response.setContentType(mimeType);
        response.setContentLength((int)file.length());

        byte[] buffer = FileCopyUtils.copyToByteArray(file);
        OutputStream os = response.getOutputStream();
        os.write(buffer);
    }

    @PostMapping("/upload/headimage")
    @ResponseBody
    public Map<String, Object> updateHeadImage(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {

        /** 封装响应结果信息 */
        Map<String, Object> result = new HashMap<>();
        /** 1、判断文件是否为空 */
        if(file.isEmpty()){
            log.error("uploadFile == 上传的文件为空！");
            result.put("code", "10001");
            result.put("msg", "请求失败， 上传的文件为空");
            return result;
        }
        /** 2、获取文件名 */
        String fileName = file.getOriginalFilename();
        /** 3、获取文件类型（扩展名），并进行校验 */
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!isValidExtension(suffixName, ALLOWED_EXTENSIONS_IMAGE)){
            log.error("文件类{}不符合要求，请重新上传！", suffixName);
            result.put("code", "10001");
            result.put("msg", "请求失败， 文件类不符合要求");
            return result;
        }
        /** 4、上传图片，并写入指定位置 */
        File desc = new File(UPLOAD_PATH_IMAGE + fileName);
        file.transferTo(desc);
        /** 5、封装成功上传的结果信息，并将图片地址返回给用户 */
        result.put("code", "200");
        result.put("url", DOWNLOAD_IMAGE_PATH + fileName);
        result.put("msg", "上传成功");

        SysUser loginUser = (SysUser) session.getAttribute("user");

        int rows = userService.updateHeadImages(loginUser.getId(), DOWNLOAD_IMAGE_PATH + fileName);

        loginUser.setHeadImages(DOWNLOAD_IMAGE_PATH + fileName);
        session.setAttribute("user", loginUser);
        return result;
    }



}
